<?php

class Payment extends CActiveRecord
{
	/**
	 * The followings are the available columns in table '{{payment}}':
	 * @var integer $id
	 * @var integer $user_id
	 * @var string $payment_date
	 * @var string $payment_sum
	 * @var integer $faktura_number
	 * @var integer $is_prepayment
	 * @var string $prepayment_date
	 * @var integer $admin_id
	 * @var string $admin_ip
	 * @var string $comment
	 * @var boolean $is_active
	 * @var string $create_time
	 * @var string $update_time
	 */
	
	public $user_contract;	//Поле для поиска и сортировки по номеру договора
	public $user_username;

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{payment}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('user_id, payment_date, payment_sum, faktura_number', 'required'),
			//array('user_id', 'validatePayment'),
			array('payment_date', 'validateDate'),
			array('payment_sum', 'validateCost'),
			array('is_prepayment', 'validatePrepayment'),
			array('prepayment_date', 'validatePrepaymentDate'),
			array('user_id, faktura_number, admin_id', 'numerical', 'integerOnly'=>true),
			array('payment_sum', 'numerical'),
			array('admin_ip', 'match', 'pattern'=>'/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/'),
			array('comment', 'length', 'max'=>128),
			array('payment_date, prepayment_date', 'type', 'type'=>'data', 'dateFormat'=>Yii::app()->locale->dateFormat),
			array('is_active, is_prepayment', 'boolean'),
			array('create_time, update_time', 'unsafe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, user_contract, user_username, user_id, payment_date, payment_sum, faktura_number, is_prepayment, prepayment_date, admin_id, admin_ip, comment, is_active, create_time, update_time', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'admin'=>array(self::BELONGS_TO,'Admin','admin_id',
					'select'=>'id,username',),
			'user'=>array(self::BELONGS_TO,'User','user_id',
					'select'=>'id,contract,username',),
			//'total'=>array(self::STAT, 'Payment', 'id', 'select'=>'SUM(payment_sum)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('main','Id'),
			'user_id' => Yii::t('main','User'),
			'payment_date' => Yii::t('main','Payment Date'),
			'payment_sum' => Yii::t('main','Payment Sum'),
			'faktura_number' => Yii::t('main','Faktura Number'),
			'is_prepayment' => Yii::t('main','Is Prepayment'),
			'prepayment_date' => Yii::t('main','Prepayment Date'), 
			'admin_id' => Yii::t('main','Admin'),
			'admin_ip' => Yii::t('main','Admin Ip'),
			'comment' => Yii::t('main','Comment'),
			'is_active' => Yii::t('main','Is Active'),
			'create_time' => Yii::t('main','Create Time'),
			'update_time' => Yii::t('main','Update Time'),
			'user_contract' => Yii::t('main','Contract'),			//Поле для поиска и сортировки по номеру договора
			'user_username' => Yii::t('main','Username'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria(array('with'=>array('user','admin')));

		$criteria->compare('t.id',$this->id);

		$criteria->compare('t.user_id',$this->user_id);
		
		$criteria->compare('user.username',$this->user_username, true);
		
		$criteria->compare('user.contract',$this->user_contract, true);

		$criteria->compare('t.payment_date',$this->payment_date,true);

		$criteria->compare('t.payment_sum',$this->payment_sum,true);

		$criteria->compare('t.faktura_number',$this->faktura_number);
		
		$criteria->compare('t.is_prepayment',$this->is_prepayment);

		$criteria->compare('admin.username',$this->admin_id, true);

		$criteria->compare('t.admin_ip',$this->admin_ip,true);

		$criteria->compare('t.comment',$this->comment,true);

		$criteria->compare('t.is_active',$this->is_active);

		$criteria->compare('t.create_time',$this->create_time,true);

		$criteria->compare('t.update_time',$this->update_time,true);

		return new CActiveDataProvider('Payment', array(
			'criteria'=>$criteria,
			'pagination'=>array('pageSize'=>Setting::get('PerPage')),
			'sort'=>array(
				'defaultOrder'=>'t.payment_date DESC',
				'attributes'=>array(
					'admin_id'=>array(
						'asc'=>'admin.username',
						'desc'=>'admin.username DESC',
					),
					'user_username'=>array(
						'asc'=>'user.username',
						'desc'=>'user.username DESC',
					),
					'user_contract'=>array(			//Поле для поиска и сортировки по номеру договора
						'asc'=>'user.contract',
						'desc'=>'user.contract DESC',
					),
					'payment_date',
					'payment_sum',
					'faktura_number',
					'is_prepayment',
					'comment',
				)
			),
		));
	}
	
	public function beforeSave()
	{
		$this->admin_id = (get_class(Yii::app())=='CConsoleApplication') ? 9999 : Yii::app()->user->id;
		if (Yii::app()->user->getState('role')==0) $this->admin_id=9999;
		$this->admin_ip = Yii::app()->request->userHostAddress;
		//throw new CHttpException(400,'ALL GOOD');

		return parent::beforeSave();
	}
	
	public function beforeDelete()
	{
		return User::model()->canChangeBalance($this->payment_sum, $this->user_id) && parent::beforeDelete(); 
	}
	
	public function afterSave()
	{
		$this->updateUserBalance();  //FIXME функция ничего не делает
		parent::afterSave();
	}
	
	public function validateCost($attribute,$params)
	{
		if ($this->isNewRecord) {
			return true;
		} else {
			if (!User::model()->canChangeBalance($this->oldAttributes[$attribute]-$this->{$attribute}, $this->user_id))
				$this->addError($attribute,'Cannot change sum, balance < 0');
		}
	}
	
	public function validateDate($attribute,$params)
	{ //FIXME можно создать авансовый платеж за сегодня, а потом поменять дату в пределах ред дата 
		$reddate = new DateTime(date('Y-m-d', CDateTimeParser::parse(Setting::get('RedDate'), Yii::app()->locale->dateFormat)));
		
		if (isset($this->{$attribute})) $date = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->{$attribute}, Yii::app()->locale->dateFormat)));
		if (isset($this->oldAttributes[$attribute])) $olddate = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->oldAttributes[$attribute], Yii::app()->locale->dateFormat)));
		
		if ($date < $reddate || (isset($olddate) && $olddate < $reddate)) {
			$this->addError($attribute,'Date is out of red Date.');
		}
	}
	
	public function validatePrepayment($attribute,$params)
	{
		$now = date_create('now');
		if ($this->isNewRecord) {
			if ($this->is_prepayment) {
				if (empty($this->prepayment_date)) {
					$date = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->payment_date, Yii::app()->locale->dateFormat)));
					date_add($date,new DateInterval('P'.Setting::get('PrePaymentDays').'D'));
					$this->prepayment_date=date_format($date, 'd.m.Y');
					//if ($date < $now) {
					//	$this->addError('is_prepayment','Prepeyment date < now');
					//	return false;
					//}
				}
			}
		} else {
			if ($this->is_prepayment && !$this->oldAttributes['is_prepayment']) {
				if (empty($this->prepayment_date)) {
					$date = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->payment_date, Yii::app()->locale->dateFormat)));
					date_add($date,new DateInterval('P'.Setting::get('PrePaymentDays').'D'));
					$this->prepayment_date=date_format($date, 'd.m.Y');
					//if ($date < $now) {
					//	$this->addError('is_prepayment','Prepeyment date < now');
					//	return false;
					//}
				}				
			}
			if (!$this->is_prepayment && $this->oldAttributes['is_prepayment']) $this->prepayment_date=NULL;
		}
	}
	
	public function validatePrepaymentDate($attribute,$params)
	{
		if (!empty($this->prepayment_date)) {
			$now = date_create('now');
			$date = new DateTime(date('Y-m-d', CDateTimeParser::parse($this->prepayment_date, Yii::app()->locale->dateFormat)));
			if ($date < $now) {
				$this->addError('prepayment_date','Prepeyment date < now');
				return false;
			}
		}			
	}
	
    public function getTotals()		//FIXME сделать статический масив типа
    {
    	$criteria=$this->search()->criteria;
    	$criteria->with='';
    	$criteria->select=new CDbExpression('SUM(payment_sum) as payment_sum');
    	return $this->find($criteria);
    }
    
	public function getTotalCost($begin, $end, $user_id)
	{
		if (!isset($begin)) $begin='0';
		$sql='select sum(payment.payment_sum) from yii_payment as payment where payment.is_active=1 and payment.payment_date between :begin and :end and payment.user_id=:user_id';
		$command = $this->dbConnection->createCommand($sql);
		$command->bindParam(':begin',date('Y-m-d',$begin));
		$command->bindParam(':end',date('Y-m-d',$end));
		$command->bindParam(':user_id',$user_id);
        return sprintf('%.3f', $command->queryScalar());
	}
	
	public function updateUserBalance()
	{
		//FIXME функция ничего не делает еще
	}
	
	public function afterFind()
	{
		$this->user_contract=$this->user_id;	//Поле для поиска и сортировки по номеру договора
		$this->user_username=$this->user_id;
		return parent::afterFind();
	}
	
	public function behaviors()
    {
        return array(
			'History' => array(
                'class'=>'application.components.behaviors.HistoryBehavior',
            ),
            'DateTime' => array(
				'class'=>'application.components.behaviors.DateTimeBehavior',
			),
			'OldAttributes' => array(
				'class'=>'application.components.behaviors.OldAttributesBehavior',
			),
            'NotActiveOnDelete' => array(
            	'class'=>'application.components.behaviors.NotActiveOnDeleteBehavior',
            ),
        );
    }
}